module MC.AudioModel {
	export class AudioBase {
		public constructor() {
			this.context = MC.AudioModel.AudioBase.InitAudioContext();
			this.init();
		}
		public context: AudioContext = null;
		static AudioContext: AudioContext = null;
		public loadComplete = false;
		static InitAudioContext(): AudioContext {
			if (!AudioBase.AudioContext) {
				let wd = <any>window;
				AudioBase.AudioContext = new (wd.AudioContext || wd.webkitAudioContext || wd.mozAudioContext || wd.msAudioContext)();
			} else {
				return AudioBase.AudioContext;
			}
			if (MC.OS.MicroMessenger) {
				document.addEventListener("WeixinJSBridgeReady", () => {
					debug.log("AudioBase.tryPlay();WeixinJSBridgeReady");
					AudioBase.tryPlay();
				}, false);
				debug.log("尝试WeixinJSBridgeReady");
			}

			return AudioBase.AudioContext;
		}

		static _tryPlay = false;
		static tryPlay() {
			if (AudioBase._tryPlay) {
				return;
			}
			AudioBase._tryPlay = true;
			debug.log("static.tryPlay();");
			let source = AudioBase.AudioContext.createBufferSource();
			var channels = 1;
			var frameCount = AudioBase.AudioContext.sampleRate * channels;
			var myArrayBuffer = AudioBase.AudioContext.createBuffer(channels, frameCount, AudioBase.AudioContext.sampleRate);
			source.buffer = myArrayBuffer;
			source.connect(AudioBase.AudioContext.destination);
			source.start(0, 0, 5);
		}
		private init() {
			let mthis = this;
			let tryfun = () => {
				document.removeEventListener('touchstart', tryfun);
				AudioBase.tryPlay();
			};
			document.addEventListener('touchstart', tryfun);
		}
		protected queueIndex: MC.createjsd.LoadQueue = null;
		protected filelist: Array<FILELIST> = [];

		/*** 加载完成后调用 */
		private _conFun: Function = null;
		/** 添加需要加载的文件 */
		public addFile(id: string, src: string) {
			this.filelist.push({
				id: id,
				src: src,
				SourceNode: null
			});
		}

		public Play(id: string): SourceNode {
			let node = this.idToSourceNode(id);
			if (node) {
				node.play();
				if (!this.isplay) {
					node.volume = -1;
				}
			} else {
				debug.log("找不到音乐:" + id);
			}
			return node;
		}

		private idToSourceNode(id: string): SourceNode {
			for (let i = 0; i < this.filelist.length; i++) {
				if (this.filelist[i].id === id) {
					return this.filelist[i].SourceNode;
				}
			}
			return null;
		}
		/*** 如果file为空字符串,则一个一个加载音频文件 */
		public load(file: string = '', fun: Function = null) {
			if (file == '') {
				this._conFun = fun;
				this.loadfile();
				return;
			}
			this.queueIndex = new MC.createjsd.LoadQueue(false);
			this.queueIndex.loadManifest(<any>this.filelist);
			this.queueIndex.loadBlobFile(file);
			this.queueIndex.on("complete", () => {
				this.loadaudioData();
			});
			this._conFun = fun;
		}
		/** 加载完成后调用 */
		private conFun() {
			this._conFun && this._conFun();
		}
		/** 一个一个加载文件 */
		private loadfile() {
			let count = this.filelist.length;
			let mthis = this;
			let _loadCount = 0;///加载个数
			for (let one of this.filelist) {
				let zip = new MC.Zip.Zblob();
				
				//console.log(one.src);
				zip.Onload = (url: any) => {
				//	console.log(mthis.context.decodeAudioData);
					mthis.context.decodeAudioData(zip.buffer,
						(buffer: AudioBuffer) => {
							//console.log(buffer,_loadCount);
							one.SourceNode = new SourceNode(buffer, mthis.context);
							_loadCount++;
							
							if (_loadCount === this.filelist.length) {
								mthis.loadComplete = true;
								mthis.conFun();
							}
						});
					///	console.log(url,zip.buffer);
				};
				zip.open(one.src);
			}
		}
		private loadaudioData() {
			let count = this.filelist.length;
			let mthis = this;
			let fun = () => {
				count--;
				if (count < 0) {//如果小于0,表示全部加载完成
					mthis.loadComplete = true;
					mthis.conFun();
					return;
				}
				let id = mthis.filelist[count].id;
				mthis.context.decodeAudioData(mthis.queueIndex.getResultBuffer(id),
					(buffer: AudioBuffer) => {
						mthis.filelist[count].SourceNode = new SourceNode(buffer, mthis.context);
						fun();
					});
			}
			fun();
		}
		private playButton: JQuery = null;
		/** 创建音乐控制按钮 */
		public createButton() {
			var musichtml = $('<div class="mp3div"><a class="mp3button play"></a></div>');
			var body = $('#indexwrapper');
			body.append(musichtml);
			let style = `<style type="text/css">
					 .mp3div{
					      width: 30px;
						height: 32px;
						position: absolute;
						left: 15px;
						top: 1.55rem;
						z-index: 1001;
					} 
					 .class_Immerse .mp3div{
						top: 70px;
					} 
					.mp3div .mp3button{
						display: block;
						width: 100%;
						height: 150%;
						display: block;
						background-size: 100% auto;
						margin: 0 auto;
						-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
						outline: none;
						margin-top: 0%;
						background-repeat: no-repeat;
					}
				</style>`;
			body.append(style);

			this.playButton = musichtml.find('.mp3div .mp3button');
			var m_this = this;
			this.playButton.click(function () {
				m_this.onClick();
			});
		 	this.isplay = true;
		}

		private onClick() {
			let is=this.isplay;
			if(is){
				MC.tongji("AudioMuted", "音乐静音");
			}else{
				MC.tongji("AudioRecovery", "音乐恢复");
			}
			this.isplay = !is;
		}
		set isplay(is: boolean) {
			if (!this.isclick) {
				return;
			}
			this.isclick = false;
			this._isPlay = is;
			if (is) {
				this.playButton.addClass('play');
				this.recovery();
			} else {
				this.playButton.removeClass('play');
				this.jingyin();
			}
		}
		get isplay() {
			return this._isPlay;
		}

		/** 是否允许点击 */
		private isclick = true;
		/** 标记是否允许播放 */
		private _isPlay = true;
		/** 静音 */
		private jingyin() {
			let volume = 1;
			let mthis = this;
			let time = setInterval(() => {
				if (time === null) {
					return;
				}
				volume -= 0.1;
				if (volume < -1) {
					volume = -1;
					clearInterval(time);
					time = null;
					mthis.isclick = true;
				}
				mthis.filelist.forEach(element => {
					element.SourceNode.volume = volume;
					//	console.log(volume);
				});
			}, 30);
		 	h5App.videoAll&&h5App.videoAll.m_videoObj&&(h5App.videoAll.m_videoObj.muted=true);
		//
		}
		/** 恢复播放音量 */
		private recovery() {
			/*
			this.isclick = true;
			this.filelist.forEach(element => {
				element.SourceNode.volume = 1;
			});
			*/
			let volume = -1;
			let mthis = this;
			let time = setInterval(() => {
				if (time === null) {
					return;
				}
				volume += 0.1;
				if (volume > 1) {
					volume = 1;
					clearInterval(time);
					time = null;
					mthis.isclick = true;
				}
				mthis.filelist.forEach(element => {
					element.SourceNode.volume = volume;
					//	console.log(volume);
				});
			}, 30);		
				h5App.videoAll&&h5App.videoAll.m_videoObj&&(h5App.videoAll.m_videoObj.muted=false);
			//	
		}
	}
	interface FILELIST {
		id: string;///文件的id
		src: string;///文件的路径
		SourceNode: SourceNode;
	}
}